/*
 * Copyright 2017 Yeolar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "raster/net/NetUtil.h"

#include <sys/utsname.h>
#include <arpa/inet.h>
#include <netdb.h>

#include "accelerator/Logging.h"

namespace rdd {

std::string getNodeName() {
  struct utsname buf;
  if (uname(&buf) != -1) {
    return buf.nodename;
  }
  return "(unknown)";
}

std::string getNodeIp() {
  static std::string ip;
  if (ip.empty()) {
    struct hostent* ent = gethostbyname(getNodeName().c_str());
    if (ent != nullptr) {
      switch (ent->h_addrtype) {
        case AF_INET:
        case AF_INET6:
          {
            char str[128];
            inet_ntop(ent->h_addrtype, ent->h_addr, str, sizeof(str));
            ip = str;
          }
          break;
        default: break;
      }
    }
  }
  return ip.empty() ? "(unknown)" : ip;
}

} // namespace rdd
